package argos.deploy;

import java.net.URL;
import java.util.List;

public class ChainClassLoader extends ClassLoader {
	private List<OpenClassLoader> loaders;
	
	public ChainClassLoader(List<OpenClassLoader> loaders) {
		super();
		this.loaders = loaders;
	}

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		for(OpenClassLoader l : loaders) {
			try {
				return l.findClass(name);
			}
			catch(ClassNotFoundException ignore) {}
		}
		throw new ClassNotFoundException(name);
	}

	@Override
	protected URL findResource(String name) {
		URL url = null;
		for(OpenClassLoader l : loaders) {
			url = l.findResource(name);
			if(url != null) {
				return url;
			}
		}
		return url;
	}

	@Override
	protected Package getPackage(String name) {
		Package pkg = null;
		for(OpenClassLoader l : loaders) {
			pkg = l.getPackage(name);
			if(pkg != null) {
				return pkg;
			}
		}
		return pkg;
	}

	@Override
	protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
		for(OpenClassLoader l : loaders) {
			try {
				return l.loadClass(name, resolve);
			}
			catch(ClassNotFoundException ignore) {}
		}
		throw new ClassNotFoundException(name);
	}

	@Override
	public Class<?> loadClass(String name) throws ClassNotFoundException {
		return loadClass(name, true);
	}
}
